<template>
    <div class="box box-primary ids">
        <div class="box-header">
            <h4 class="text-primary text-center">录像通道</h4>
        </div>
        <div class="box-body">
            <div class="form-inline" autocomplete="off" spellcheck="false">
                <div class="form-group form-group-sm">
                    <label>搜索</label>
                    <input type="text" class="form-control" placeholder="关键字" v-model.trim="q" ref="search" @keydown.enter.prevent>
                </div>
            </div>
            <div class="clearfix"></div>
            <br>
            <el-table :data="pageData" stripe  :default-sort="{prop: 'id', order: 'ascending'}" @sort-change="sortChange" v-loading="loading" element-loading-text="加载中...">
                <el-table-column min-width="100" label="通道号" prop="id"  show-overflow-tooltip sortable></el-table-column>
                <el-table-column min-width="200" label="通道名称" prop="name"  show-overflow-tooltip></el-table-column>
				<el-table-column min-width="230" label="操作" :fixed="isMobile() ? false : 'right'">
                    <template slot-scope="scope">
                        <div class="btn-group">
                            <router-link :to="`/record/timeview/${scope.row.id}`" class="btn btn-primary btn-xs"
                                v-if="scope.row.updateAt && scope.row.updateAt !== '0001-01-01 00:00:00'">
                                <i class="fa fa-file-video-o"></i> 查看录像
                            </router-link>
                            <router-link :to="`/playback/timeview/${scope.row.id}`" class="btn btn-info btn-xs"
                                v-if="scope.row.online && (scope.row.type.endsWith('SDK') || scope.row.type == 'ISUP')">
                                <i class="fa fa-video-camera"></i> 设备录像
                            </router-link>
                            <a role="button" class="btn btn-danger btn-xs" @click.prevent="remove(scope.row)"
                                v-if="hasAnyRole(serverInfo, userInfo, '管理员') && scope.row.updateAt && scope.row.updateAt !== '0001-01-01 00:00:00'">
                                <i class="fa fa-remove"></i> 删除
                            </a>
                        </div>
                    </template>
				</el-table-column>
                <el-table-column min-width="100" label="快照">
                    <template slot-scope="props">
                        <el-popover :open-delay="1000" :close-delay="10" placement="left" :title="`[${props.row.id}] ${props.row.name}`" width="400" trigger="hover">
                            <img onerror="this.src='/images/default_snap.png';" style="width:100%;height:100%;" :src="props.row.snapURL">
                            <img onerror="this.src='/images/default_snap.png';" style="height:30px;width:50px;" slot="reference" :src="props.row.snapURL">
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column min-width="120" label="在线状态" prop="online"  show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span class="text-primary" v-if="scope.row.online">在线</span>
                        <span class="text-gray" v-else>离线</span>
                    </template>
                </el-table-column>
                <el-table-column prop="updateAt" min-width="200" label="更新时间" sortable="custom" :formatter="formatUpdateTime"
                    v-if="serverInfo.VersionType != '标准版'">
                </el-table-column>
            </el-table>
        </div>
        <div class="box-footer clearfix" v-if="total > 0">
            <el-pagination layout="total,prev,pager,next" :pager-count="isMobile() ? 3 : 5" class="pull-right" :total="total" :page-size.sync="pageSize" :current-page.sync="page"></el-pagination>
        </div>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import _ from 'lodash'
import $ from 'jquery'

export default {
    data() {
        return {
            pageSize: 10,
            q: "",
            page: 1,
            pageData: [],
            total: 0,
            sort: 'id',
            order: 'ascending',
            loading: false,
        }
    },
    mounted() {
        // this.$refs['search'].focus();
        // this.load();
    },
    computed: {
        ...mapState(['serverInfo', 'userInfo'])
    },
    methods: {
        ready(){
            this.$watch('q', function() {
                this.doDelaySearch();
            });
            this.$watch('page', function(val) {
                this.doSearch(val);
            });
        },
        isMobile() {
            return videojs.browser.IS_IOS||videojs.browser.IS_ANDROID;
        },
        load(global = true) {
            if(global) {
                this.loading = true;
            }
            $.ajax({
                method: "GET",
                url: "/api/v1/record/querydevices",
                global: global,
                data: {
                    start: (this.page -1) * this.pageSize,
                    limit: this.pageSize,
                    q: this.q,
                    sort: this.sort,
                    order: this.order
                }
            }).then(data => {
                this.pageData = data.rows;
                this.total = data.total;
            }).always(() => {
                if(global) {
                    this.$nextTick(() => {
                        this.loading = false;
                    })
                }
            })
        },
        formatUpdateTime(row, col, cell) {
            if(cell) {
                if(cell === "0001-01-01 00:00:00") {
                    return "-";
                }
                return cell;
            };
            return "-";
        },
        sortChange(data) {
            this.sort = data.prop;
            this.order = data.order;
            this.load();
        },
        selectDevice(id){
            this.$emit("select-device", id);
        },
        doSearch(page = 1) {
            var query = {};
            if(this.q) query["q"] = this.q;
            this.$router.replace({
                path: `/record/channels/${page}`,
                query: query
            });
        },
        doDelaySearch: _.debounce(function() {
            this.doSearch();
        }, 500),
        async remove(row) {
            this.$confirm(`删除 ${row.name} ,会将设备所有录像删除，确认继续?`, '提示').then(() => {
                $.get("/api/v1/record/removedevice", {
                    id: row.id
                }).always(() => {
                    this.load();
                })
            }).catch(() => {})
        }
    },
    beforeRouteEnter(to, from, next) {
        next(vm => {
            vm.q = to.query.q || "";
            vm.page = parseInt(to.params.page) || 1;
            vm.ready();
        })
    },
    beforeRouteUpdate(to, from, next) {
        next();
        this.$nextTick(() => {
            this.q = to.query.q || "";
            this.page = parseInt(to.params.page) || 1;
            this.pageData = [];
            this.total = 0;
            this.load();
        })
    }
}
</script>
